import { Component } from 'react';
import styles from '../replay/style.less';
import zoomInImg from '@/assets/camera/zoom_in.png';
import zoomOutImg from '@/assets/camera/zoom_out.png';

class CameraTimeRule extends Component {
  constructor(props) {
    super(props);
    this.state = {
      height: 65,
      width: 120,
      canvasHeight: 50,
      canvasWidth: 120,
      maxScale: 24,
      startValue: 0,
      region: false,
      background: '#000000',
      color: false,
      markColor: '#FFCC33',
      isConstant: false,
      intervalWidth: 30,
      rulerWrap: null, // 获取容
      canvas: null,
      cxt: null,
      minSildeNum: 0,// 最小滑动的值
      maxSildeNum: 200,// 最大滑动的值
      scaleValueList: [],
      timeSale: 600,
      initX: 0,
      initXTemp: 0,
      endX: 0,
      distanceX: 0,
      distanceXTemp: 0,
      lastX: 0,
      isMouseDown: false,
      count: 0,
      timeType: 1,
      bigGridTime: 0,
      gridTotal: 0,
      offsetTime: 0,
      offsetPx: 0,
      offsetPxLast: 0,
      curMouseX: 0,
    };
  }

  async componentDidMount() {
    const rulerWrap = document.getElementById('rulerText'); // 获取容器
    const { intervalWidth } = this.state;
    rulerWrap.style.height = this.state.height < 50 ? `${50}px` : `${this.state.height}px`;
    let maxScale = 24 * 3600 / this.state.timeSale;
    await this.setStateAsync({
      maxScale,
    });
    let minSildeNum = 0;
    let maxSildeNum = maxScale;
    if (this.state.region) {
      minSildeNum = Math.floor(this.state.region[0]);
      maxSildeNum = Math.floor(this.state.region[1]);
      await this.setStateAsync({
        minSildeNum,
        maxSildeNum,
      });
    }

    const count = this.state.startValue; // 初始值
    await this.setStateAsync({
      count,
    });

    const winWidth = rulerWrap.offsetWidth; // 容器宽度

    // 刻度值数组
    const scaleValueList = [];
    for (let i = 0; i <= this.state.maxScale; i++) {
      scaleValueList.push(i);
    }
    await this.setStateAsync({
      scaleValueList,
    });

    let canvas = rulerWrap.getElementsByTagName('canvas')[0]; // 获取容器下的canvas标签
    // if (!canvas) {
    //   canvas = document.createElement('canvas'); // 创建canvas标签
    //   canvas.width = winWidth;
    //   canvas.height = this.state.height;
    //   rulerWrap.appendChild(canvas);
    // }

    const cxt = canvas.getContext('2d');
    let devicePixelRatio = 1;
    if (window.devicePixelRatio) {
      devicePixelRatio = window.devicePixelRatio;
    }
    const canvasWidth = winWidth * window.devicePixelRatio;
    const canvasHeight = this.state.height * window.devicePixelRatio;
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    cxt.scale(devicePixelRatio, devicePixelRatio);
    // canvas.style.transform = `scale(${1 / devicePixelRatio})`;
    canvas.style.transformOrigin = 'left top';

    await this.setStateAsync({
      width: winWidth,
      canvasWidth,
      canvasHeight,
      canvas,
      cxt,
    });
    this.changeTimeType(this.state.timeType)
    this.drawRuler(count);
    const that = this;
    // 手指按下
    canvas.addEventListener('touchstart', async function(e) {
      console.log("touchstart")
      console.log(e)
      await that.setStateAsync({
        initX: e.targetTouches[0].pageX,
      });
    }, false);

    // 手指滑动
    canvas.addEventListener('touchmove', async function(e) {
      console.log("touchmove")
      console.log(e)
      await that.setStateAsync({
        endX: e.targetTouches[0].pageX,
      });
      that.moveEvent();
    }, false);

    // 手指抬起
    canvas.addEventListener('touchend', async function(e) {
      console.log("touchend")
      console.log(e)
      await that.setStateAsync({
        lastX: that.state.count,
      });
      that.overEvent();
    }, false);

    // 鼠标按下
    canvas.addEventListener('mousedown', async function(e) {
      if(that.canMoveWithCenter(e.layerX)){
        await that.setStateAsync({
          isMouseDown: true,
          initXTemp: e.layerX,
          initX: e.layerX,
        });
      }
    }, false);

    // 鼠标移动
    canvas.addEventListener('mousemove', async function(e) {
      if (!that.state.isMouseDown) {
        await that.setStateAsync({
          curMouseX: e.layerX,
          initX: that.state.initXTemp,
        });
        that.drawRuler(0)
        return false;
      }
      if(that.canMoveWithCenter(that.state.width/2)){
        await that.setStateAsync({
          endX: e.layerX,
        });
        that.moveEvent();
      }
    }, false);


    // 鼠标抬起&离开
    canvas.addEventListener('mouseup', async function(e) {
      await that.setStateAsync({
        isMouseDown: false,
      });
      that.overEvent();
    }, false);

    canvas.addEventListener('mouseleave', async function(e) {
      if(that.state.initXTemp === e.pageX){
        return;
      }
      if (that.state.isMouseDown) {
        if(that.canMoveWithCenter(that.state.width/2)){
          await that.setStateAsync({
            lastX: that.state.count,
            isMouseDown: false,
          });
          that.overEvent();
        }
      }else{
        await that.setStateAsync({
          curMouseX: 0,
        });
        that.drawRuler(0);
      }
    }, false);
  }

  // 手指&鼠标移动事件
  async moveEvent() {
    const {initX,endX,offsetTime,offsetPx,offsetPxLast,bigGridTime,gridTotal,gridWidth} = this.state;
    let offsetTimeTemp =  (endX - initX) / gridWidth * bigGridTime;
    let offsetPxTemp = endX - initX;
    await this.setStateAsync({
      offsetPx: offsetPxTemp+offsetPxLast,
    })
    this.drawRuler(0);
  }

  // 手指&鼠标结束事件
  async overEvent() {
    const {initX,endX,offsetTime,offsetPx,offsetPxLast,bigGridTime,gridTotal,gridWidth} = this.state;
    let offsetTimeTemp =  (endX - initX) / gridWidth * bigGridTime;
    let offsetPxTemp =  endX - initX;
    await this.setStateAsync({
      offsetPxLast: offsetPxLast + offsetPxTemp,
      offsetPx: offsetPxLast + offsetPxTemp,
      curMouseX: 0,
    })
    this.drawRuler(0);
    // 返回最后的值
    if (this.props.selectTime !== undefined) {
      this.props.selectTime(this.getFullTimeForCenter(this.state.width/2));
    }
  }

  setStateAsync(state) {
    return new Promise((resolve) => {
      this.setState(state, resolve);
    });
  }

  getTimeText(time,hasSecond) {
    let hour = 0;
    let minute = 0;
    let second = 0;
    second = time;
    if (second >= 3600) {
      minute = (second - (second % 60)) / 60;
      hour = parseInt((minute / 60).toString());
      minute = minute % 60;
      /* eslint-disable */
      hour >= 10 ? hour : hour = '0' + hour;
      minute >= 10 ? minute : minute = '0' + minute;
      second = second % 60;
      second >= 10 ? second : second = '0' + second;
      /* eslint-enable */
      if(hasSecond){
        return hour + ':' + minute + ':'+ second;
      }
      return hour + ':' + minute;
    }
    if (second < 3600 && second >= 60) {
      hour = '00';
      minute = parseInt((second / 60).toString());
      /* eslint-disable */
      minute >= 10 ? minute : minute = '0' + minute;
      second = second % 60;
      second >= 10 ? second : second = '0' + second;
      /* eslint-enable */
      if(hasSecond){
        return hour + ':' + minute + ':'+ second;
      }
      return hour + ':' + minute;
    }
    if (second < 60) {
      hour = '00';
      minute = '00';
      second = parseInt(second);
      second >= 10 ? second : second = '0' + second;
      if(hasSecond){
        return hour + ':' + minute + ':'+ second;
      }
      return hour + ':' + minute;
    }
  }

  /**
   * 左侧开始时间的偏移，返回单位ms
   */
  startOffsetTime(timestamp, step) {
    let remainder = timestamp % step;
    return remainder ? step - remainder : 0;
  }

  async changeTimeType(timeType){
    let gridTotal = 12;
    let bigGridTime = 0;
    if(timeType === 1){// 2小时间隔
      bigGridTime = 7200;
    }else if(timeType === 2){// 1小时间隔
      bigGridTime = 3600;
    }else if(timeType === 3){// 30分钟间隔
      bigGridTime = 1800;
    }else if(timeType === 4){// 10间隔
      bigGridTime = 600;
    }
    const gridWidth = this.state.width / gridTotal
    await this.setStateAsync({
      bigGridTime,
      gridTotal,
      gridWidth,
    })
  }

  getFullTimeWithPx(curPx){
    const {bigGridTime,gridWidth,offsetPxLast} = this.state;
    const totalPx = curPx - offsetPxLast;
    const totalSeconds = Math.floor(totalPx * (bigGridTime/gridWidth))
    return this.getTimeText(totalSeconds,true)
  }

  getFullTimeForCenter(curPx){
    const {bigGridTime,gridWidth,offsetPx} = this.state;
    const totalPx = curPx - offsetPx;
    const totalSeconds = Math.floor(totalPx * (bigGridTime/gridWidth))
    return this.getTimeText(totalSeconds,true)
  }

  canMoveWithCenter(curPx){
    const {bigGridTime,gridWidth,offsetPx} = this.state;
    const totalPx = curPx + offsetPx;
    const totalSeconds = 24*3600 - Math.floor(totalPx * (bigGridTime/gridWidth))
    return true;
    // if(totalSeconds>0&&totalSeconds<24*3600){
    //   return true;
    // }else {
    //   return false;
    // }
  }

  getDateSeconds(dateStr){
    const date = new Date(Date.parse(dateStr.replace(/-/g,   "/")))
    return date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds()
  }

  getRecordWith(record){
    const startTime = this.getDateSeconds(record.startTime);
    const endTime = this.getDateSeconds(record.endTime);
    const {bigGridTime,gridWidth,offsetPx} = this.state;
    const startPx = Math.floor(startTime*gridWidth/bigGridTime)+offsetPx;
    const endPx = Math.floor(endTime*gridWidth/bigGridTime)+offsetPx;
    return {start:startPx,end:endPx};
  }

  drawRuler(countTemp) {
    // width: 宽度; ms：一个小刻度的秒数 pxMs：10像素一个小刻度 pageShowStartTime：初始时间（毫秒）
    const {width,offsetTime,offsetPx,cxt, canvas} = this.state;
    // 1天
    let pageShowStartTime = 0; // 开始时间
    let bigGrid = 24*3600 / bigGridTime;
    let smallGrid = 6;  // 一个大格子有多少个小格子
    let smallGridTime = bigGridTime/smallGrid; // 一个小格子的时长

    const {bigGridTime,gridTotal,gridWidth} = this.state;

    // 清空画布
    cxt.clearRect(0, 0, this.state.canvasWidth, this.state.canvasHeight);
    // 刻度尺背景
    if (this.state.background) {
      cxt.fillStyle = this.state.background;
      cxt.fillRect(0, 0, this.state.canvasWidth, this.state.canvasHeight);
    }

    let msOffset = offsetTime; // this.startOffsetTime(pageShowStartTime, ms); // 开始的偏移时间 ms
    let pxOffset = offsetPx; // msOffset * pxMs; // 开始的偏移距离 px
    let leftDistance = 0; // 到左侧的距离
    let leftDistanceTime = 0; // 到左侧的时间
    for (let i = 0; i < gridTotal+1; i++) {
      leftDistance = pxOffset%gridWidth + i * gridWidth; // 距离 = 开始的偏移距离 + 格数 * px/格
      if(pxOffset<0){
        leftDistanceTime = (Math.abs(Math.floor(pxOffset/gridWidth))+i-1) * bigGridTime; // 时间 = 左侧开始时间 + 偏移时间 + 格数 * ms
      }else {
        leftDistanceTime = (Math.abs(Math.floor(pxOffset/gridWidth))+i) * bigGridTime; // 时间 = 左侧开始时间 + 偏移时间 + 格数 * ms
      }
      // console.log(leftDistance + '====' + leftDistanceTime)
      cxt.beginPath();
      cxt.save();
      cxt.strokeStyle = this.state.color ? this.state.color : '#bbb';
      cxt.lineWidth = 1;
      cxt.lineCap = 'round';
      cxt.moveTo(leftDistance, Math.floor(this.state.height * 0.7));
      cxt.lineTo(leftDistance, this.state.height);
      cxt.font = '8pt Arial Bold';
      const midText = this.getTimeText(leftDistanceTime,false);
      cxt.fillStyle = '#FFFFFF';
      cxt.fillText(midText, leftDistance - cxt.measureText(midText).width / 2, this.state.height*0.7 - 5);

      // if (showTime % (smallGrid*smallGridTime) === 0) {
      //   cxt.moveTo(leftDistance, Math.floor(this.state.height * 0.3));
      //   cxt.lineTo(leftDistance, this.state.height - 20);
      //   cxt.font = '10pt Arial Bold';
      //   const midText = this.getTimeText(showTime);
      //   cxt.fillStyle = '#FFFFFF';
      //   cxt.fillText(midText, leftDistance - cxt.measureText(midText).width / 2, this.state.height - 5);
      // }else{
      //   cxt.moveTo(leftDistance, Math.floor(this.state.height * 0.5));
      //   cxt.lineTo(leftDistance, this.state.height - 20);
      // }
      cxt.stroke();
      cxt.restore();
      cxt.closePath();
    }

    // 中心刻度线
    cxt.beginPath();
    cxt.save();
    cxt.strokeStyle = this.state.markColor;
    cxt.lineWidth = 2;
    cxt.lineCap = 'round';
    cxt.moveTo((this.state.width / 2), 0);
    // cxt.lineTo((this.state.width / 2), Math.floor(this.state.height * 0.52));
    cxt.lineTo((this.state.width / 2), this.state.height);
    // 绘制中心时间
    const centTime = this.getFullTimeForCenter(this.state.width / 2)
    cxt.fillStyle = '#FFFFFF';
    cxt.font = '12pt Arial Bold';
    cxt.fillText(centTime, this.state.width/2 - cxt.measureText(centTime).width / 2, 25);

    // 绘制移动的时间
    if (!this.state.isMouseDown && this.state.curMouseX>0) {
      const curTime = this.getFullTimeWithPx(this.state.curMouseX)
      cxt.fillStyle = '#FFFFFF';
      cxt.font = '8pt Arial Bold';
      cxt.fillText(curTime, this.state.curMouseX - cxt.measureText(curTime).width / 2, 10);
    }

    // 中间两个横线
    cxt.strokeStyle = '#EBE84D'
    cxt.moveTo(0, this.state.height*0.7);
    cxt.lineTo(width, this.state.height*0.7);
    cxt.moveTo(0, this.state.height*0.8);
    cxt.lineTo(width, this.state.height*0.8);

    // 绘制可用时间线
    cxt.fillStyle = '#2eabff';
    const {recordList} = this.props;
    recordList.forEach((item) => {
      const recordData = this.getRecordWith(item)
      if(recordData.end > 0 && recordData.start < width){
        const start = recordData.start;
        const w = recordData.end - recordData.start
        cxt.fillRect(start,this.state.height*0.7,w,this.state.height*0.1);
      }
    })

    cxt.stroke();
    cxt.restore();
    cxt.closePath();
  }

  drawRuler1(countTemp) {
    const count = countTemp;
    const division = this.state.canvasWidth / this.state.intervalWidth; // 每个刻度的距离 分割线

    // 清空画布
    const { cxt, canvas } = this.state;
    cxt.clearRect(0, 0, this.state.canvasWidth, this.state.canvasHeight);
    // 刻度尺背景
    if (this.state.background) {
      cxt.fillStyle = this.state.background;
      cxt.fillRect(0, 0, this.state.canvasWidth, this.state.canvasHeight);
    }
    // 画刻度线
    for (let i = 0; i < this.state.maxScale+1; i++) {
      cxt.beginPath();
      cxt.save();
      cxt.strokeStyle = this.state.color ? this.state.color : '#bbb';
      cxt.lineWidth = 1;
      cxt.lineCap = 'round';
      const x = division * i - count * division;
      // 刻度值
      cxt.font = '10pt Arial Bold';
      const midText = this.getTimeText(count * this.state.timeSale + i * this.state.timeSale,false);
      cxt.fillStyle = '#FFFFFF';
      cxt.fillText(midText, x - cxt.measureText(midText).width / 2, this.state.height - 5);
      if (i % 10 === 0) {
        cxt.strokeStyle = this.state.color ? this.state.color : '#666';
        cxt.moveTo(x, Math.floor(this.state.height * 0.5));
      } else if (i % 2 === 0) {
        cxt.strokeStyle = this.state.color ? this.state.color : '#999';
        cxt.moveTo(x, Math.floor(this.state.height * 0.4));
      } else {
        cxt.moveTo(x, Math.floor(this.state.height * 0.5));
      }
      cxt.lineTo(x, this.state.height - 20);
      cxt.stroke();
      cxt.restore();
      cxt.closePath();
    }
    // 中心刻度线
    cxt.beginPath();
    cxt.save();
    cxt.strokeStyle = this.state.markColor;
    cxt.lineWidth = 2;
    cxt.lineCap = 'round';
    cxt.moveTo((this.state.width / 2), 0);
    // cxt.lineTo((this.state.width / 2), Math.floor(this.state.height * 0.52));
    cxt.lineTo((this.state.width / 2), this.state.height);
    cxt.stroke();
    cxt.restore();
    cxt.closePath();
  }

  async handlZoomIn(){
    if(this.state.timeType < 4) {
      await this.setStateAsync({
        timeType: this.state.timeType+1
      })
      this.changeTimeType(this.state.timeType);
      this.drawRuler(0)
    }
  }

  async handlZoomOut(){
    if(this.state.timeType > 1) {
      await this.setStateAsync({
        timeType: this.state.timeType-1
      })
      this.changeTimeType(this.state.timeType);
      this.drawRuler(0)
    }
  }

  render() {
    return (
      <div className={styles.timeRuleRoot}>
        <div className={styles.timeRule} id={'rulerText'}>
          <canvas id='canvas' style={{width:'100%',height:'100%'}}></canvas>
        </div>
        <div className={styles.timeRuleAction}>
          <img onClick={(event) =>this.handlZoomIn()}  className={styles.timeRuleImg} src={zoomInImg}/>
          <img onClick={(event) =>this.handlZoomOut()} className={styles.timeRuleImg} src={zoomOutImg}/>
        </div>
      </div>
    );
  }
}

export default CameraTimeRule;
